package com.myjob.controller;

import com.myjob.entity.Company;
import com.myjob.entity.User;
import com.myjob.enums.RedisEnums;
import com.myjob.exception.OptionException;
import com.myjob.handlerImpl.UploadHandlerImpl;
import com.myjob.response.Result;
import com.myjob.service.CompanyService;
import com.myjob.service.UserService;
import com.myjob.utils.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author Chen Yuan
 * @create 2021-01-23  14:57
 */
@RestController
@Slf4j
@RequestMapping("/company")
public class CompanyController {
	@Autowired
	private CompanyService companyService;
	@Autowired
	private UploadHandlerImpl uploadImage;
	@Autowired
	private UserService userService;

	/**
	 * 查询所有企业信息
	 * @param currentPage 当前页面
	 * @param pageSize 每页大小
	 * @param searchValue 筛选条件
	 * @param companyName 企业名称
	 * @param financingSituation 融资情况
	 * @param companySize 企业规模
	 * @param enterprisesType 企业类型
	 * @param memberLevel 会员等级
	 * @param companyStatus 企业状态
	 * @return 封装好的结果
	 */
	@GetMapping("/companyInfo")
	public Result selectCompanies(@RequestParam("currentPage")Integer currentPage,
	                              @RequestParam(value = "pageSize", required = false)Integer pageSize,
	                              @RequestParam(value = "searchValue", required = false)String searchValue,
	                              @RequestParam(value = "companyName", required = false)String companyName,
	                              @RequestParam(value = "financingSituation", required = false)String financingSituation,
	                              @RequestParam(value = "companySize", required = false)String companySize,
	                              @RequestParam(value = "enterprisesType", required = false)String enterprisesType,
	                              @RequestParam(value = "memberLevel", required = false)String memberLevel,
	                              @RequestParam(value = "companyStatus", required = false)String companyStatus,
								  @RequestParam(value = "companyAddress", required = false)String companyAddress){
		Result result = null;
		try {
			List<String> statusList = new ArrayList<>();
			if (UtilValidate.isNotEmpty(companyStatus)) {
				statusList = Arrays.asList(companyStatus.split(","));
			}
			result = companyService.selectCompanies(currentPage, pageSize, searchValue,
													companyName, financingSituation,companySize,
													enterprisesType, memberLevel, statusList, companyAddress);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@GetMapping("/selectOneCompany")
	public Result selectOneCompany(@RequestParam("companyId") String companyId){
		Result result = null;
		try {
			Company company = companyService.selectOneCompany(companyId);
			if (UtilValidate.isEmpty(company)) {
				result = Result.failed("查询失败，无此企业");

			}else if (UtilValidate.isEmpty(company.getCompanyName())) {
				// 如果名字为空，则表示还未创建企业信息
				result = Result.failed("未创建企业信息");

			}else {
				result = Result.succeed(company, "按照编号查询企业成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new OptionException("按照编号查询企业失败");
		}
		return result;
	}

	/**
	 * 添加企业
	 * @param company 企业信息
	 * @return  影响行数
	 */
	@PutMapping("/companyInfo")
	public Result addCompany(@RequestBody Company company){
		Result result = null;
		try {
			int insert = companyService.addCompany(company);
			if (insert == 1){
				result = Result.succeed("企业 添加 成功");
			}else {
				result = Result.failed("企业 添加 失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 更新企业信息
	 * @param company 企业信息
	 * @return 影响行数
	 */
	@PostMapping("/companyInfo")
	public Result updateCompany(@RequestBody Company company){
		Result result = null;
		try {
			int update = companyService.updateCompany(company);
			if (update == 1){
				result = Result.succeed("企业 修改 成功");
			}else {
				result = Result.failed("企业 修改 失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 删除企业
	 * @param companyId 企业编号
	 * @return 影响行数
	 */
	@DeleteMapping("/companyInfo")
	public Result deleteCompany(@RequestParam("companyId") Long companyId){
		Result result = null;
		try {
			int delete = companyService.deleteCompany(companyId);
			if (delete == 1){
				result = Result.succeed("企业 删除 成功");
			}else {
				result = Result.failed("企业 删除 失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


	@PostMapping("/image")
	public Result uploadImage(@RequestParam("photo") MultipartFile photo,
	                          @RequestParam("type") String type,
	                          @RequestParam(value = "userId", required = false) String UserId) {
		String logoPrefix = "null";
		// 按照传类的 type 值，匹配输出不同的图片前缀
		if (Objects.equals(type, "companyLogo")) {
			// 获取企业 Logo 文件前缀
			logoPrefix = RedisEnums.KEY_IN_REDIS.COMPANY_LOGO.getValue();
		} else if (Objects.equals(type, "companyPhoto")) {
			// 获取企业 照片 文件前缀
			logoPrefix = RedisEnums.KEY_IN_REDIS.COMPANY_PHOTO.getValue();
		} else if (Objects.equals(type, "userPhoto")) {
			// 获取用户 照片 文件前缀
			logoPrefix = RedisEnums.KEY_IN_REDIS.USER_PHOTO.getValue();
		}else if (Objects.equals(type, "advertisementPhoto")){
			// 获取广告 照片 文件前缀
			logoPrefix = RedisEnums.KEY_IN_REDIS.ADV_PHOTO.getValue();
		}
		String result = uploadImage.uploadImage(photo, logoPrefix, UserId);
		return Result.succeed(result);
	}


	@PostMapping("/getFollowedList")
	public Result getFollowedList(@RequestParam(value = "userId") String userId){
		Result result = null;
		try {
			if (UtilValidate.isEmpty(userId)) {
				return Result.succeed(new ArrayList<>(), "用户名为空");
			}
			User user = userService.getById(userId);
			String follows = user.getFollows();
			if (UtilValidate.isEmpty(follows)) {
				return Result.succeed(new ArrayList<>(),"收藏为空");
			}
			List<String> followedList = Arrays.asList(follows.split(","));
			if (UtilValidate.isEmpty(followedList)) {
				result = Result.succeed(new ArrayList<>(),"收藏为空");
			}else {
				result = Result.succeed(followedList);
			}
		}catch (Exception e){
		    e.printStackTrace();
		    throw new OptionException("查询收藏企业失败");
		}
		return result;
	}

	@PostMapping("/followCompany")
	public Result followCompany(@RequestParam(value = "userId") String userId,
								@RequestParam(value = "companyId") String companyId){
		Result result = null;
		try {
			User user = userService.getById(userId);
			String follows = user.getFollows();
			if (UtilValidate.isNotEmpty(follows)) {
				follows += companyId+",";
			}else {
				follows = companyId+",";
			}
			user.setFollows(follows);
			boolean b = userService.updateById(user);
			if (b){
				result = Result.succeed("收藏成功");
			}else {
				result = Result.failed("收藏失败");
			}
		}catch (Exception e){
		    e.printStackTrace();
		    throw new OptionException("收藏企业失败");
		}
		return result;
	}


	@PostMapping("/cancelFollowCompany")
	public Result cancelFollowCompany(@RequestParam(value = "userId") String userId,
								@RequestParam(value = "companyId") String companyId){
		Result result = null;
		try {
			User user = userService.getById(userId);
			String follows = user.getFollows();
			String replace = follows.replace(companyId + ",", "");
			user.setFollows(replace);
			boolean b = userService.updateById(user);
			if (b){
				result = Result.succeed("取消收藏成功");
			}else {
				result = Result.failed("取消收藏失败");
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new OptionException("取消收藏企业失败");
		}
		return result;
	}

	@GetMapping("/getFollowedList")
	public Result followCompanyInfoList(@RequestParam("currentPage")Integer currentPage,
	                                    @RequestParam(value = "pageSize", required = false)Integer pageSize,
	                                    @RequestParam(value = "searchValue", required = false)String searchValue,
	                                    @RequestParam(value = "userId") String userId){
		Result result = null;
		try {
			User user = userService.getById(userId);
			String follows = user.getFollows();
			if (UtilValidate.isEmpty(follows)) {
				return Result.succeed(null, "企业收藏夹为空");
			}

			List<String> followedList = Arrays.asList(follows.split(","));

			result = companyService.getFollowCompanyInfoList(currentPage, pageSize,
													searchValue, followedList);

		}catch (Exception e){
			e.printStackTrace();
			throw new OptionException("收藏企业失败");
		}
		return result;
	}



	@GetMapping("/countCompany")
	public Result countCompany() {
		Result result = null;
		try {
			result = companyService.countCompany();
		} catch (Exception e) {
			e.printStackTrace();
			throw new OptionException("查询失败");
		}
		return result;
	}

}
